const csv = require('csvtojson');
const fs = require('fs');
const axios = require('axios')




let bodyTemp_numberSegment = [
    {
        name: "number_segment_set_total",
        type: "gauge",
        metricsLabels: [
            {
                labelName: "provinceCode",
                labelValue: "451"
            },
            {
                labelName: "nodeId",
                labelValue: "DB451"
            },
            {
                labelName: "sectionNo",
                labelValue: "1301821"
            }
        ],
        value: 10000
    },

    {
        name: "number_segment_set_remain",
        type: "gauge",
        metricsLabels: [
            {
                labelName: "provinceCode",
                labelValue: "451"
            },
            {
                labelName: "nodeId",
                labelValue: "DB451"
            },
            {
                labelName: "sectionNo",
                labelValue: "1301821"
            }
        ],
        value: 7000
    },

    {
        name: "number_segment_set_used",
        type: "gauge",
        metricsLabels: [
            {
                labelName: "provinceCode",
                labelValue: "451"
            },
            {
                labelName: "nodeId",
                labelValue: "DB451"
            },
            {
                labelName: "sectionNo",
                labelValue: "1301821"
            }
        ],
        value: 3000
    }
];

async function readDataFromCsv(filePath) {
    return csv().fromFile(filePath)
        .subscribe(json => {
            return new Promise((resolve, reject) => {
                if (!json) {
                    reject('read csv error')
                } else {
                    resolve(json)
                }
            })
        })
}


const provinceValueIncrementMap = {
    100: 1000,
    200: 1500,
    431: 2000,
    451: 2500,
    311: 3000,
    951: 3500,
    971: 4000,
    731: 4500,
}

async function sendMetrics(numberSegment, nodeId, provinceCode, incrementValue) {
    let bodyTemp_tmp = JSON.parse(JSON.stringify(bodyTemp_numberSegment))
    for (let i = 0; i < bodyTemp_tmp.length; i++) {
        let item = bodyTemp_tmp[i]
        for (let j = 0; j < item.metricsLabels.length; j++) {
            let y = item.metricsLabels[j];
            if (y.labelName == "provinceCode") {
                y.labelValue = provinceCode;
            }
            if (y.labelName == "nodeId") {
                y.labelValue = nodeId;
            }
            if (y.labelName == "sectionNo") {
                y.labelValue = numberSegment;
            }
        }
        if (item.name == 'number_segment_set_total') {
            item.value = segmentTotalValue + provinceValueIncrementMap[provinceCode] + incrementValue;
        } else if (item.name == 'number_segment_set_remain') {
            item.value = segmentRemainlValue + provinceValueIncrementMap[provinceCode] + incrementValue;
        } else {
            item.value = segmentUsedValue + provinceValueIncrementMap[provinceCode] + incrementValue;
        }
    }
    bodyTemp_tmp.forEach(m => {
        resultArr.push(m);
    })
}



async function batchSendMetrics(year, month, day) {

    nodeList.filter(x => {
        if (!nodeId || nodeId === '') {
            return true;
        } else {
            return nodeId == x.code;
        }
    }).forEach(nodeInfo => {
        let provinceList = nodeInfo.province.split(',');
        provinceList.filter(x => {
            if (!provinceCode || provinceCode == "") {
                return true;
            } else {
                return x == provinceCode;
            }
        }).forEach(p => {
            console.log(nodeInfo.code, p)
            numberSegmentList.forEach(async n => {
                await sendMetrics(n.segment, nodeInfo.code, p, 200);
            })
        })

    })

    let jsonTmp = JSON.stringify(resultArr)

    // fs.writeFile("numberSegment.txt", jsonTmp, error => {
    //     if (error) throw error;
    // })

    segmentTotalValue = 10000;
    segmentRemainlValue = 7000;
    segmentUsedValue = 3000;
    resultArr = new Array();

    let reportTime = year + month + day + '0100' + '00';

    customConfig = {
        headers: {
            'Content-Type': 'application/json',
            'reportTime': reportTime
        }
    };

    const resp = await axios.post(REQ_URL, jsonTmp, customConfig);
}


/**
 * config 信息 ==================
 */
let year = "2023";
// order total
let segmentTotalValue = 10000;
let segmentRemainlValue = 7000;
let segmentUsedValue = 3000;

// 填写具体的端节点ID，为空字符串时代表所有端节点ID
// 填写具体的省份编码，为空字符串代表所有的省份
const nodeId = "";
const provinceCode = "";
const REQ_URL = 'http://15.116.20.124:30061/metrics/report';
// const REQ_URL = 'http://localhost:8080/metrics/report';

let resultArr = new Array();


function sleep(time) {
    return new Promise((resolve, reject) => {
        return setTimeout(resolve, time);
    });
}

let nodeList;
let numberSegmentList;
async function batchSendMetricsLoop() {
    nodeList = await readDataFromCsv(__dirname + '/../node-server-info/en_endnode.csv');
    numberSegmentList = await readDataFromCsv(__dirname + "/./segment.csv")
    let days = [31,28,31,30,31,30,31,31,30,31,30,31] 
    
    ourter:
    for (let i = 0; i < days.length; i++) {
        let month = i.toString().padStart(2, '0');
        reportMonth = month;
        let day = days[i-1];
        for (let j = 1; j <= day; j++) {
            let dayStr = j.toString().padStart(2, '0');
            reportDay = dayStr;
            await batchSendMetrics(year, month, dayStr);
            // break ourter;
        }
        
    }
    reportMonth = '';
    reportDay = '';
}

// batchSendMetricsLoop();

let reportMonth = '';
let reportDay = '';

async function execReport() {
    if (reportMonth === '' && reportDay === '') {
        batchSendMetricsLoop();
        return 'start...'
    } else {
        return 'server count: ' + reportMonth + ", " + reportDay;
    }
}

exports.execReport = execReport;